package com.yycx.module.bus.provider.handler.haiying.tasktodo.order;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yycx.bpm.provider.constant.FlowableConstant;
import com.yycx.bpm.provider.handler.TaskCompleteHandler;
import com.yycx.bpm.provider.model.TaskRequest;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.security.OpenUser;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.DateUtil;
import com.yycx.common.utils.DateUtils;
import com.yycx.common.utils.RedisUtils;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.mapper.BaseRoleUserMapper;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.BusOrder;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.provider.handler.haiying.BusinessUtils;
import com.yycx.module.bus.provider.service.BusOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import com.yycx.module.bus.provider.service.hy.HyRemoteOrderService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.provider.service.SysCompanyService;
import com.yycx.msg.provider.websocket.WebSocketServerEndpoint;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取任务表单数据
 *
 * @author zyf
 */
@Component
@DSTransactional
public class HyOrderTaskDataHandler implements TaskCompleteHandler {


    @Resource
    private WebSocketServerEndpoint socketServerEndpoint;

    @Resource
    private HyRemoteOrderService hyRemoteOrderService;


    @Resource
    private HyOrderService orderService;
    @Resource
    private BusinessUtils businessUtils;

    @Resource
    private RedisUtils redisUtils;


    @Resource
    private BaseUserService userService;

    //是否是同步模式
    private Boolean syncTag=true;

    @Override
    public Map<String, Object> initTaskData(ProcessInstance processInstance, Task task, Map<String, Object> variables) {
        Map<String, Object> ret = new HashMap<>(5);
        String businessKey = processInstance.getBusinessKey();

        return ret;
    }

    @Override
    public ResultBody prepare(TaskRequest taskRequest, ProcessInstance processInstance, Task task, Map<String, Object> completeVariables, OpenUser user) {
        return TaskCompleteHandler.super.prepare(taskRequest, processInstance, task, completeVariables, user);
    }

    /**
     * 表单提交后业务处理
     *
     * @param taskRequest
     * @param processInstance
     * @param task
     * @param completeVariables
     */
    @Override
    public void completeAfter(TaskRequest taskRequest, ProcessInstance processInstance, Task task, Map<String, Object> completeVariables, OpenUser user) {
        //系统配置
        EntityMap config = redisUtils.getConfigMap("DBR_CONFIG");
        //税率
        Integer sync = config.getInt("sync", 0);
        if (sync.equals(1)) {
            String businessKey = processInstance.getBusinessKey();
            HyOrder order = orderService.getById(businessKey);
            String name = task.getName();
            String taskKey = task.getTaskDefinitionKey();
            String rule = "审核通过:{0}.{1}. {2}";
            BaseUser baseUser = userService.getUserByUsername(user.getUsername());
            String nickName = baseUser.getApplyName();
            String approveDate = DateUtils.formatDate(DateUtils.getNowDateTime(),"yyyy-MM-dd HH:mm:ss");
            EntityMap entity = new EntityMap();
            String message = taskRequest.getMessage();
            entity.put("orderId", businessKey);
            String comments = MessageFormat.format(rule, message, nickName, approveDate);
            if (taskKey.equals("__initiator__")&&syncTag.equals(false)) {
                //同步在单数
                businessUtils.syncUseNum(order);
            }
            if (name.equals("销售服务部复核")) {
                entity.put("comments", comments);
                order.setCommentsXs(comments);
                //hyRemoteOrderService.updateXsComments(dbName, entity);
                orderService.updateById(order);
            }
            if (name.equals("商务中心商控员")) {
                entity.put("approveDate", approveDate);
                entity.put("nickName", nickName);
                entity.put("comments", "审核通过:" + message);
                order.setCommentsSw(nickName + "#" + approveDate + "#" + "审核通过:" + message);
                //hyRemoteOrderService.updateJsComments(dbName, entity);
                orderService.updateById(order);
            }
            if (name.equals("财务复核员")) {
                entity.put("comments", comments);
                order.setCommentsCw(comments);
                //hyRemoteOrderService.updateCwComments(dbName, entity);
                orderService.updateById(order);
            }
        }
    }

    @Override
    public void backAfter(TaskRequest taskRequest, Task task, OpenUser user, String targetActivityId) {
        //系统配置
        EntityMap config = redisUtils.getConfigMap("DBR_CONFIG");
        //税率
        Integer sync = config.getInt("sync", 0);
        if (sync.equals(1)) {
            String name = task.getName();
            EntityMap entity = new EntityMap();
            String businessKey = taskRequest.getBusinessKey();
            HyOrder order = orderService.getById(businessKey);
            entity.put("orderId", businessKey);
            if (targetActivityId.equals("__initiator__") &&syncTag==false) {
                //删除在单数
                businessUtils.removeRemoteOrder(order);
            }
            if (name.equals("销售服务部复核") || targetActivityId.equals(FlowableConstant.INITIATOR)) {
                entity.put("comments", "");
                //hyRemoteOrderService.updateXsComments(dbName, entity);
                order.setCommentsXs(null);
                orderService.updateById(order);
            }
            if (name.equals("商务中心商控员") || targetActivityId.equals(FlowableConstant.INITIATOR)) {
                entity.put("nickName", "");
                entity.put("comments", "");
                entity.put("approveDate", "");
                order.setCommentsSw(null);
                orderService.updateById(order);
                // hyRemoteOrderService.updateJsComments(dbName, entity);
            }
            if (name.equals("财务复核员") || targetActivityId.equals(FlowableConstant.INITIATOR)) {
                entity.put("comments", "");
                order.setCommentsCw(null);
                orderService.updateById(order);
                //hyRemoteOrderService.updateCwComments(dbName, entity);
            }
        }
        TaskCompleteHandler.super.backAfter(taskRequest, task, user, targetActivityId);
    }
}
